import requests
import json
import csv

# 用于存储所有数据的列表
all_data = []
num = 1

while True:
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0',
    }

    try:
        response = requests.get(
            f"https://datacenter-web.eastmoney.com/api/data/v1/get?callback=datatable4715646&columns"
            f"=REPORT_DATE%2CTIME%2CDOMESTICL_PRODUCT_BASE%2CFIRST_PRODUCT_BASE%2CSECOND_PRODUCT_BASE"
            f"%2CTHIRD_PRODUCT_BASE%2CSUM_SAME%2CFIRST_SAME%2CSECOND_SAME%2CTHIRD_SAME&pageNumber="
            f"{num}&pageSize=20&sortColumns=REPORT_DATE&sortTypes=-1&source=WEB&client=WEB&reportName"
            f"=RPT_ECONOMY_GDP&p=2&pageNo=2&pageNum=2&_=1743590062406", headers=header)

        if response.status_code != 200:
            print(f"状态码:{response.status_code}")
            break

        data_text = response.text.split('(')[1].split(')')[0]
        data_json = json.loads(data_text)
        page_data = data_json['result']['data']

        all_data.extend(page_data)
        num += 1

        if num >= 5:
            break

    except requests.RequestException as e:
        print(f"请求发生错误: {e}")
        break
    except (IndexError, KeyError, json.JSONDecodeError) as e:
        print(f"数据解析错误: {e}")
        break


if all_data:
    headers = all_data[0].keys()
    with open('GDP.csv', 'w', encoding='utf-8', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=headers)
        writer.writeheader()
        writer.writerows(all_data)

    print("数据已成功保存到 GDP.csv 文件中。")
else:
    print("未获取到有效数据。")















